<template>
  <div style="text-align: center">
    <el-container>
      <el-main>
        <el-row>
          <el-col :span="12" class="fir_col"></el-col>
        </el-row>
        <el-row class="sec_row">
          <el-col class="sec_row_col1" :span="6">
            <h1></h1>
          </el-col>
          <el-col class="sec_row_col2" :span="12">
            <el-form
              ref="stall"
              :model="stall"
              label-width="80px"
              :rules="rules"
            >
              <div style="text-align: right">
                <el-form-item>
                  <el-switch
                    v-model="value1"
                    active-text="出租车位"
                    inactive-text="停止租用"
                    @change="changeStallState()"
                  >
                  </el-switch>
                </el-form-item>
              </div>
              <el-form-item label="小区选择">
                <el-select
                  v-model="stall.management_id"
                  placeholder="选择小区"
                  filterable
                  @change="getselected(stall.management_id)"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in managements"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="车位大小">
                <!-- <el-input
                  v-model="stall.stall_size"
                  placeholder="车位大小"
                ></el-input> -->
                <el-select
                  v-model="stall.stall_size"
                  placeholder="车位大小"
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in stallSizes"
                    :key="item.key"
                    :label="item.value"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="车位编号" prop="stall_code">
                <el-input
                  v-model="stall.stall_code"
                  placeholder="例如:A001"
                ></el-input>
              </el-form-item>

              <el-form-item label="车位价格" prop="stall_price">
                <el-input
                  v-model="stall.stall_price"
                  placeholder="车位价格"
                ></el-input>
              </el-form-item>

              <el-form-item label="车位描述">
                <el-input
                  v-model="stall.evaluate"
                  placeholder="车位描述"
                ></el-input>
              </el-form-item>

              <el-form-item label="上传照片">
                <!-- <input type="file" @change="getFile($event)" /> -->

                <el-upload
                  :action="reqUrl"
                  list-type="picture-card"
                  :http-request="uploadSectionFile"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  @click="handleSaveClick('stall')"
                  round
                  :disabled="!isResponed"
                  >发布车位</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      for (var i = this.stalls.length-1; i >=0; i--) {
        if (this.stalls[i].stall_code == value) {
          callback(new Error("该车位编号已被使用"));
        }
      }

      callback();
    };
    return {
      stallSizes: [
        { key: 1, value: "大" },
        { key: 2, value: "中" },
        { key: 3, value: "小" },
      ],
      rules: {
        stall_code: [
          { required: true, message: "请输入车位编号", trigger: "blur" },
         
          { min: 2, max: 4, message: "长度在2到4个字符", tregger: "blur" },
          {
            pattern: /^[A-Z][0-9]{2,3}$/,
            message: "车位标号只能是字母开头的,其余的为数字",
          },
           { validator: validatePass, trigger: "blur" },
          
        ],
        stall_price: [
          { required: true, message: "请输入车位价格", trigger: "blur" },
          {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: "请输入正确的价格",
          },
        ],
      },
      uid: "",
      reqUrl: "",
      form: {
        name: "",
        region: "",
        region1: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
        stallNumber: "",
      },
      isResponed:true,
      input: "",
      stalls: [],
      stall: {
        stall_size: "",
        stall_code: "",
        stall_price: "",
        evaluate: "",
        photo: "",
        management_id: "",
        stall_user_id: "",
        stall_state: "空闲",
      },
      managements: "",
      selectManagement_id: "", //所选择的物业的id
      value1: true,
      imageUrl: "",
    };
  },
  methods: {
    handleSaveClick(formName) {
      this.isResponed=false;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.stall.stall_user_id = sessionStorage.getItem("userId");
          let formData = new FormData();

          formData.append("stall_size", this.stall.stall_size);
          formData.append("stall_code", this.stall.stall_code);
          formData.append("stall_price", this.stall.stall_price);
          formData.append("evaluate", this.stall.evaluate);
          //将文件封装到formData类型的对象中，名称为headimg1
          //headimg1是一个自定义名称，需要和服务器端接收文件的参数名称吻合
          formData.append("stallphoto", this.stall.photo);
          formData.append("management_id", this.stall.management_id);
          formData.append("stall_user_id", this.stall.stall_user_id);
          formData.append("stall_state", this.stall.stall_state);
          let config = {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          };
          this.addDialogFormVisible = false;

          this.$axios
            .post("/stall", formData, config)
            .then((res) => {
              
               this.$message({
                message: res.data.messages,
                type: "success",
              });

              this.stall.stall_code = "";
              this.$axios
                .get("/getStallsByManagementId/" + this.stall.management_id)
                .then((res) => {
                  this.stalls = res.data.data;
                  this.isResponed=true;
                })
                .catch((res) => {
                  this.isResponed=true;
                });
            })
            .catch((err) => {
              this.$message({
                message: err.data.messages,
                type: "warning",
              });
              this.isResponed=true;
            });
        } else {
          this.isResponed=true;
          this.$message.error("填写信息错误");
        }
      });
    },
    uploadSectionFile(params) {
      this.stall.photo = params.file;
    },

    getFile(e) {
      this.stall.photo = e.target.files[0];
    },
    onSubmit() {
    },

    onLoadManagements() {
      this.uid = sessionStorage.getItem("userId");
      this.$axios
        .get("/managements")
        .then((res) => {
          this.managements = res.data.data;
        })
        .catch((err) => {});
    },
    getselected(data) {
      this.$axios
        .get("/getStallsByManagementId/" + data)
        .then((res) => {
          this.stalls = res.data.data;
        })
        .catch((err) => {});
    },

    changeStallState() {
      if (this.value1 == true) {
        this.stall.stall_state = "空闲";
      } else {
        this.stall.stall_state = "停用";
      }
    },
    addStall() {
      this.stall.stall_user_id = sessionStorage.getItem("userId");
      this.$axios
        .post("/stall", this.stall)
        .then((res) => {
          this.$message({
            message: res.data.messages,
            type: "success",
          });
        })
        .catch((err) => {
          this.$message({
            message: err.data.messages,
            type: "warning",
          });
        });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },

  mounted() {
    this.onLoadManagements();
  },
  watch: {},
};
</script>

<style>
.el-col {
  min-height: 1px;
}
.sec_row {
  height: 100px;
  text-align: top;
}
.sec_col_row {
  height: 50px;
}
.sec_col1 {
  background-color: pink;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>